package com.noah.bee.core.zookeeper;

import com.noah.bee.core.exception.BeeException;
import com.noah.bee.core.support.PlaceholderChangeEvent;
import com.noah.bee.core.support.PlaceholderChanger;
import com.noah.bee.core.util.DecryptByDataBizUtil;
import com.noah.bee.core.util.InitPath2PathUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;

/**
 * @author wuzhen
 * @since 16/12/19 15:32
 */

public class ZkContainer {

    private static final Logger logger = LoggerFactory.getLogger(ZkContainer.class);

    // spring默认单例，instance对象会被多线程共享，添加volatile关键字是的线程每次对instance属性的修改都会被刷新到堆内存中，而不保留当前线程栈中的副本，并且线程每次获取时也会直接从主存中取值，而不会再使用线程栈中的副本值（其实从另一个维度解决多线程变量共享的问题）
    private static volatile ZkContainer instance;

    private static Map<String, String> cache;

    private CuratorFramework client;

    /**
     * zookeeper中存放属性节点的路径,如: /apps/jobapp/properties
     */
    private String propertiesRootPath;

    private List<PlaceholderChanger> changers = new CopyOnWriteArrayList<>();

    static {
        cache = new ConcurrentHashMap<>();

    }

    private ZkContainer() {
        this.propertiesRootPath = ZkPath.forAppProperties(Environment.getAppName()); // 获取app名字，并拼接zk节点路径
        this.client = CuratorFrameworkFactory.builder().connectString(Environment.getZkServer())
                .retryPolicy(new ExponentialBackoffRetry(2000, 3)).connectionTimeoutMs(3000)//.sessionTimeoutMs()
                .build(); // 构建zk客户端对象
        this.client.start();
        // 读取当前app节点下面的所有配置项到本地缓存（ConcurrentHashMap）
        synchronize();
        watch();
    }

    // 获取zk的客户端实例，先判断空，再加锁，防止加锁期间被其他线程初始化，再判空一次
    public static ZkContainer getInstance() {
        if (null == instance) {
            synchronized (ZkContainer.class) {
                if (null == instance) {
                    instance = new ZkContainer();
                }
            }
        }
        return instance;
    }

    public void addChanger(PlaceholderChanger changer) {
        this.changers.add(changer);
    }

    /**
     * get value from zookeeper
     * 从缓存中根据属性名称获取属性值，如果当前缓存中不存在当前值，从zk中获取一次
     *
     * @param name property name
     * @return value
     */
    public String getProperty(String name) {
        String value = cache.get(name);
//        if (null == value) {
//            value = getZkValue(completePath(name));
//            if (null != value) cache.put(name, value);
//        }
        return value;
    }

    /**
     * 根据绝对路径获取data值
     *
     * @param path node path
     * @return value
     */
    private String getZkValue(String path) {
        String value = null;
        try {
            byte[] bytes = client.getData().forPath(path);
            if (null != bytes) {
                value = new String(bytes, "UTF-8");
            }
        } catch (KeeperException.NoNodeException e) {
            logger.warn("not exist node(" + path + "):" + e.getMessage());
        } catch (Exception e) {
            logger.error("get node(" + path + ") error:" + e.getMessage());
            throw new BeeException("get node(" + path + ") error:" + e.getMessage());
        }
        return value;
    }

    /**
     * 获取 property name所指向的zk 节点的完整路径
     * 将properties name作为节点名称，属性值作为data存放
     * @param propertyName 属性名称,如: "user.name"
     * @return path, 如: "/apps/app01/properties/user.name"
     */
    private String completePath(String propertyName) {
        return propertiesRootPath + ((propertyName.startsWith("/")) ? "" : "/") + propertyName;
    }


    /**
     * 系统启动后从zookeeper同步数据到本地缓存
     */
    private void synchronize() {
        try {
            // 优先获取databiz host做加解密用
            String dataBizApiHost = getZkValue(completePath("base.dataBiz.apiHost"));

            // 获取propertiesRootPath下面所有子节点
            List<String> childPaths = client.getChildren().forPath(propertiesRootPath);
            if (!(null == childPaths || childPaths.isEmpty())) {
                for (String path : childPaths) {
                    // 获取属性的值，比如jdbc.password=12345678
                    String value = getZkValue(completePath(path)); // 拼接zk绝对路径并获取data
                    if (null != value) {
                        if (path.startsWith("decryption")) { // 以decryption开头的表示需要加解密
                            value = DecryptByDataBizUtil.decryptStr(value, dataBizApiHost);
                        }

                        if(path.endsWith("reinit")){
                            path = InitPath2PathUtil.initPath2Path(path);
                        }
                        cache.put(ZkPath.getLastSubPath(path), value);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("synchronized properties in path(" + propertiesRootPath + ") from zookeeper failure:" + e.getMessage());
        }
    }

    /**
     * 启动监听器，监听当前应用在zookeeper对应目录下的所有子节点(属性名称)的变化:
     * /apps/app01/properties 下的所有属性节点的变化,如: .../x,.../y,.../z
     */
    private void watch() {
        // Curator中的path cache，监听propertiesRootPath的子节点的更新，删除和增加。原生态的zk watch为一次性监听，使用过后即失效，但是cache监听为持续监听，避免了重复注册watch，并且将变更数据也带到了客户端，这是原生的api没有的
        // 每个监听都会额外的产生一个线程
        final PathChildrenCache childCache = new PathChildrenCache(client, propertiesRootPath, true);
        try {
            childCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
            // 增加listener监听缓存改变
            childCache.getListenable().addListener(new PathChildrenCacheListener() {
                // 回调事件
                @Override
                public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                    String propertyNodeName = (null == event.getData()) ? null : ZkPath.getLastSubPath(event.getData().getPath());
//                    if(propertyNodeName != null && propertyNodeName.endsWith("reinit")){
//                        propertyNodeName = InitPath2PathUtil.initPath2Path(propertyNodeName);
//                    }
                    switch (event.getType()) {
                        // 判断通知类型
                        // 子节点变更或者新增
                        case CHILD_ADDED:
                        case CHILD_UPDATED:
                            String value = (null == event.getData()) ? "" : new String(event.getData().getData());
                            if (null != propertyNodeName && propertyNodeName.length() > 0) {
                                // 更新本地缓存
                                cache.put(propertyNodeName.endsWith("reinit") ? InitPath2PathUtil.initPath2Path(propertyNodeName) : propertyNodeName, propertyNodeName.startsWith("decryption")  ? DecryptByDataBizUtil.decryptStr(value.toString(), cache.get("base.dataBiz.apiHost")) : value);
                                triggerChangers(new PlaceholderChangeEvent(propertyNodeName, new String(event.getData().getData()), PlaceholderChangeEvent.ChangeType.PROPERTY_UPDATED));
                            }
                            break;
                        case CHILD_REMOVED:
                            if (null != propertyNodeName && propertyNodeName.length() > 0) {
                                cache.remove(propertyNodeName.endsWith("reinit") ? InitPath2PathUtil.initPath2Path(propertyNodeName) : propertyNodeName);
                                triggerChangers(new PlaceholderChangeEvent(propertyNodeName, PlaceholderChangeEvent.ChangeType.PROPERTY_REMOVED));
                            }
                            break;
                        case CONNECTION_RECONNECTED: // 重新连接事件通知
                            childCache.rebuild();
                            logger.info("rebuild listener after reconnected from zookeeper(" + Environment.getZkServer() + ")");
                            break;
                        case CONNECTION_SUSPENDED: // 连接暂停
                        case CONNECTION_LOST: // 连接丢失
                            logger.warn("disconnected from zookeeper server(" + Environment.getZkServer() + ")");
                            break;
                        default:
                            break;
                    }
                }
            }, Executors.newFixedThreadPool(3)); // 创建一个线程固定大小为3的线程池来处理监听事件
        } catch (Exception e) {
            throw new BeeException("starting watcher to listen zookeeper failure:" + e.getMessage());
        }
    }

    /**
     * 触发变化事件
     */
    private void triggerChangers(PlaceholderChangeEvent event) {
        if (null == changers || changers.size() == 0) return;

        for (PlaceholderChanger changer : changers) {
            changer.onChange(event);
        }
    }

}
